package com.yanxu.threadandobjectmethods.print;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/3/20-2025
 * @Description: 使用 wait、notify 交替打印，程序没有任何的问题。
 *       （对之前的问题已经进行了修改。）
 */
public class TurnsPrintByWaitNotifyFixed {
    static int a = 0;
    static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                while (a < 100) {
                    synchronized (lock) {
                        System.out.println(Thread.currentThread().getName() + "---" + a);
                        a++;
                        lock.notify();
                        try {
                            //只有 a 还小于100 的情况下，才进行wait
                            if (a < 100) {
                                lock.wait();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "偶数线程");

        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                while (a < 100) {
                    synchronized (lock) {
                        System.out.println(Thread.currentThread().getName() + "---" + a);
                        a++;
                        lock.notify();
                        try {
                            //只有 a 还小于100 的情况下，才进行wait
                            if (a < 100) {
                                lock.wait();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "奇数线程");

        thread1.start();
        Thread.sleep(200);
        thread2.start();
    }

    /*if (a < 100) {
        lock.wait();
    }*/
}

